import { Action, getModule, Module, Mutation, VuexModule } from 'vuex-module-decorators';

import { getCompanyInfo, getPageMenu } from '@/api/menu';
import { store } from '@/store';
import { ICompany, IMenu, MenuType } from '@/models/menu.interface';

export interface IMenuState {
  pageMenu: IMenu[];
  userMenu: IMenu[];
  otherMenu: IMenu[];
  allMenu: IMenu[];
  companyInfo: ICompany;
  activeIndex: string;
  interceptRoutes: number[];
}

@Module({ dynamic: true, namespaced: true, store, name: 'menu' })
class Menu extends VuexModule implements IMenuState {
  pageMenu: IMenu[] = [];
  userMenu: IMenu[] = [];
  otherMenu: IMenu[] = [];
  get allMenu(): IMenu[] {
    return [...this.pageMenu, ...this.userMenu, ...this.otherMenu];
  }
  get interceptRoutes(): number[] {
    return [...this.pageMenu, ...this.userMenu, ...this.otherMenu].filter(menu => menu.isAuth).map(menu => menu.id);
  }
  companyInfo: ICompany = {} as ICompany;
  activeIndex = '';

  @Mutation
  setPageMenu(menus: IMenu[] = []) {
    this.pageMenu = menus;
  }

  @Mutation
  setUserMenu(menus: IMenu[] = []) {
    this.userMenu = menus;
  }

  @Mutation
  setOtherMenu(menus: IMenu[] = []) {
    this.otherMenu = menus;
  }

  @Mutation
  setCompanyInfo(info: ICompany) {
    this.companyInfo = info;
  }

  @Mutation
  setActiveIndex(activeIndex = '') {
    this.activeIndex = activeIndex;
  }

  @Action
  private getMenus(type: MenuType) {
    const params = {
      type,
    };
    return getPageMenu(params);
  }

  @Action
  async getPageMenu() {
    await this.getMenus('home').then(res => {
      const { data } = res;
      this.setPageMenu(data.data);
    });
  }

  @Action
  async getUserMenu() {
    await this.getMenus('userCent').then(res => {
      const { data } = res;
      this.setUserMenu(data.data);
    });
  }

  @Action
  async getOtherMenu() {
    await this.getMenus('router').then(res => {
      const { data } = res;
      this.setOtherMenu(data.data);
    });
  }

  @Action
  async getCompanyInfo() {
    await getCompanyInfo().then(res => {
      const { data } = res;
      this.setCompanyInfo(data.data);
    });
  }
}

export const menuStore = getModule<Menu>(Menu);
